# 线性回归的4种方法
# 方法4：采用 sklearn的LinearRegression


import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score


def func(x, w, b):
    return x * w + b


# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    # print_hi('PyCharm')

    m = 101
    x_train = np.linspace(-1, 1, m)
    x_train = x_train.reshape(-1, 1)
    print(x_train.shape)
    y_train = 2 * x_train + np.random.randn(*x_train.shape) * 0.33

    ##########################################################方法3，采用sklearn
    model = LinearRegression(fit_intercept=True, normalize=False)
    model.fit(x_train, y_train)  #模型回归
    print(model.coef_, model.intercept_) # 输出模型参数

    zz = model.predict(x_train)
    R2 = model.score(x_train, y_train)
    r2 = r2_score(y_train, zz)
    mse = mean_squared_error(y_train, zz)

    print('********')
    print('R2:', R2)
    print('r2:', r2)
    print('mse:', mse)
    print('********')
    plt.figure(3)
    plt.scatter(x_train, y_train)
    plt.plot(x_train, zz, c='k')
    # plt.pause(1)
    plt.show()

